package com.yc.rh.utils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

public class ReflectUtils {
	@SuppressWarnings("rawtypes")
	public static <T> T regInfo(HttpServletRequest request, Class<T> c){
		String key;
		List<String> setMethodName=new ArrayList<String>();
		String methodName=null;
		T t=null;
		try {
			Enumeration em = request.getParameterNames();
			while(em.hasMoreElements()){
				key=(String)em.nextElement();
				setMethodName.add("set"+key);
			}
			
			 t=c.newInstance();
			
			//获取给定类的方法
			Method[] methods=c.getMethods();
			
			int startindex;
			int endindex;
			String typeName=null;		//方法的类型名
			String obj=null;			
			for(Method md:methods){
				String smd=String.valueOf(md);
				methodName=md.getName();
				for(String smn:setMethodName){
					if(smn.equalsIgnoreCase(methodName)){
						startindex=smd.indexOf(methodName)+methodName.length()+1;
						endindex=smd.indexOf(")");
						typeName=smd.substring(startindex,endindex);
						obj=request.getParameter(smn.substring(3));
						
						if(obj!=null && !"".equals(obj)){
							if("java.lang.String".equals(typeName)){
								md.invoke(t, obj);
							}else if("int".equals(typeName)){
								md.invoke(t, Integer.parseInt(String.valueOf(obj)));
							}else if("java.lang.Double".equals(typeName)){
								md.invoke(t, Double.parseDouble(String.valueOf(obj)));
							}else{
								md.invoke(t, obj);
							}
						}
						break;
					}
				}
			}
			//list.add(t);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return t;
	}
}
